package com.rytx.web.controller.ysp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.rytx.common.annotation.Log;
import com.rytx.common.core.controller.BaseController;
import com.rytx.common.core.domain.AjaxResult;
import com.rytx.common.core.domain.model.ArtUser;
import com.rytx.common.core.domain.model.LoginUser;
import com.rytx.common.core.page.TableDataInfo;
import com.rytx.common.enums.BusinessType;
import com.rytx.common.exception.ServiceException;
import com.rytx.common.exception.user.UserPasswordNotMatchException;
import com.rytx.common.utils.poi.ExcelUtil;
import com.rytx.framework.web.service.TokenService;
import com.rytx.system.domain.dto.UserRegistrationDTO;
import com.rytx.system.domain.vo.ArtUserVo;
import com.rytx.system.service.IArtUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

/**
 * 用户信息Controller
 * 
 * @author rytx
 * &#064;date  2024-04-29
 */
@RestController
@RequestMapping("/system/artuser")
public class ArtUserController extends BaseController
{
    @Autowired
    private IArtUserService artUserService;

    @Resource
    @Qualifier("ArtAuthenticationManager")
    private AuthenticationManager authenticationManager;
    @Autowired
    private TokenService tokenService;

    @PostMapping("/login")
    public AjaxResult login(@Valid @RequestBody ArtUser artUser) {
        // 用户验证
        Authentication authentication;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(artUser.getUserPhone(),artUser.getUserPassword()));
        } catch (Exception e) {
            if(e instanceof BadCredentialsException){
                throw new UserPasswordNotMatchException();
            }else{
                throw new ServiceException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String token = tokenService.createToken(loginUser);
        ArtUserVo artUserVo = new ArtUserVo();
        BeanUtil.copyProperties(artUserVo, loginUser.getArtUser());
        // 生成token
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user",artUserVo);
        return AjaxResult.success("登录成功", map);
        }

        //注册
        @PostMapping("/register")
        public AjaxResult register(@Valid @RequestBody UserRegistrationDTO artUser) {
            ArtUser artUser2 = artUserService.selectArtUserByPhone(artUser.getUserPhone());
            if(ObjectUtil.isNotNull(artUser2))return AjaxResult.error("手机号已注册！");
            //获取验证码
            String code = "000000";//redis中获取验证码
            if(StrUtil.isBlank(code))return AjaxResult.error("验证码已失效！");
            if(!code.equals(artUser.getSmsCode()))return AjaxResult.error("验证码错误！");
            //加密密码
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String password = bCryptPasswordEncoder.encode(artUser.getUserPassword());
            ArtUser au = new ArtUser();
            au.setUserPassword(password);
            au.setUserPhone(artUser.getUserPhone());
            int i = artUserService.insertArtUser(au);
            if(i<=0)return AjaxResult.error("注册失败！");
            return AjaxResult.success("注册成功！", i);
        }


        @PostMapping("/saveAddress")
        public AjaxResult saveAddress(@RequestBody ArtUser artUser) {
            LoginUser loginUser = getLoginUser();
            ArtUser artUser1 = loginUser.getArtUser();
            artUser1.setUserAddress(artUser.getUserAddress());
            return AjaxResult.success(artUserService.updateArtUser(artUser1));
        }

    /**
     * 查询用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:artuser:list')")
    @GetMapping("/list")
    public TableDataInfo list(ArtUser artUser)
    {
        startPage();
        List<ArtUser> list = artUserService.selectArtUserList(artUser);
        return getDataTable(list);
    }

    /**
     * 导出用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:artuser:export')")
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ArtUser artUser)
    {
        List<ArtUser> list = artUserService.selectArtUserList(artUser);
        ExcelUtil<ArtUser> util = new ExcelUtil<>(ArtUser.class);
        util.exportExcel(response, list, "用户信息数据");
    }

    /**
     * 获取用户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:artuser:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(artUserService.selectArtUserById(id));
    }

    /**
     * 新增用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:artuser:add')")
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ArtUser artUser)
    {
        return toAjax(artUserService.insertArtUser(artUser));
    }

    /**
     * 修改用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:artuser:edit')")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ArtUser artUser)
    {
        return toAjax(artUserService.updateArtUser(artUser));
    }

    /**
     * 删除用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:artuser:remove')")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(artUserService.deleteArtUserByIds(ids));
    }

    @GetMapping("/getUserList")
    public AjaxResult getUserList() {
        return success(artUserService.selectArtUserListShort(new ArtUser()));
    }
}
